package com.ruoyi.zsyh.controller.applet.store;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.K100Utils;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 服务订单 -- 配件单
 */
@Controller
@RequestMapping("/applet/zsyh/serviceOrderParts")
public class ZsyhServiceOrderPartsAppletController extends BaseController
{

    @Autowired
    private IZsyhServiceOrderPartsService zsyhServiceOrderPartsService;

    @Autowired
    private IZsyhServiceOrderPartsRelService zsyhServiceOrderPartsRelService;

    @Autowired
    private IZsyhServiceOrderPartsLogService zsyhServiceOrderPartsLogService;

    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;

    @Autowired
    private IZsyhServiceOrderLogService zsyhServiceOrderLogService;

    @Autowired
    private IZsyhAfterLogisticsCompanyService zsyhAfterLogisticsCompanyService;

    @Autowired
    private IZsyhServiceOrderService zsyhServiceOrderService;

    @Autowired
    private RedisUtil redisUtils;

    @Autowired
    private K100Utils k100Utils;


    /**
     * 维修师傅 订单中心 申请配件
     * @return
     * @throws Exception
     */
    @RepeatSubmit
    @Transactional
    @RequestMapping("/applyOrderParts")
    @ResponseBody
    public AjaxResult applyOrderParts(String orderId, String userId, String imagesMachine, String imagesCode, String imagesFault,
           String userName, String userPhone, String userAddress, String faultDescription, String partsJson)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();//师傅的店铺id
        ZsyhServiceOrder order = zsyhServiceOrderService.selectZsyhServiceOrderById(orderId);
        ZsyhServiceOrderParts _orderParts = new ZsyhServiceOrderParts();
        _orderParts.setOrderId(orderId);
        List<ZsyhServiceOrderParts> orderPartsList = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(_orderParts);
        int size = orderPartsList.size() + 1;
        String orderPartsId = orderId + "_P";
        if(size < 10){
            orderPartsId += "00" + size;
        }else{
            orderPartsId += "0" + size;
        }

        ZsyhServiceOrderParts orderParts = new ZsyhServiceOrderParts();
        orderParts.setId(orderPartsId);
        orderParts.setOrderId(orderId);
        orderParts.setFactoryId(order.getFactoryId());
        orderParts.setRepairId(repairId);
        orderParts.setImagesMachine(imagesMachine);
        orderParts.setImagesCode(imagesCode);
        orderParts.setImagesFault(imagesFault);
        orderParts.setUserName(userName);
        orderParts.setUserPhone(userPhone);
        orderParts.setUserAddress(userAddress);
        orderParts.setFaultDescription(faultDescription);

        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(partsJson, new TypeReference<List<Map<String, Object>>>() {});
        List<ZsyhServiceOrderPartsRel> relList = new ArrayList<>();

        //申请状态 1待审核 2待发件 3已发件 4已返件待确认 5审核拒绝 6已完结
        String partsState = "6";
        for(Map<String, Object> a:list){
            BigDecimal partsMoneyRepair = BigDecimal.ZERO;
            BigDecimal partsMoneyFactory = BigDecimal.ZERO;
            String afterPartsId = String.valueOf(a.get("afterPartsId"));
            String _partsMoneyRepair = String.valueOf(a.get("partsMoneyRepair"));
            String _partsMoneyFactory = String.valueOf(a.get("partsMoneyFactory"));
            long partsNum = Integer.valueOf(String.valueOf(a.get("partsNum")));
            String isSelfParts = String.valueOf(a.get("isSelfParts"));//是否允许使用自购件 1是 0否
            if(EmptyUtils.isNotEmpty(_partsMoneyRepair)){
                partsMoneyRepair = new BigDecimal(_partsMoneyRepair);
            }
            if(EmptyUtils.isNotEmpty(_partsMoneyFactory)){
                partsMoneyFactory = new BigDecimal(_partsMoneyFactory);
            }
            if("0".equals(isSelfParts)){//只要有一个不允许使用自购件，配件申请单就是等待厂家审核状态
                partsState = "1";
            }
            ZsyhServiceOrderPartsRel partsRel = new ZsyhServiceOrderPartsRel();
            partsRel.setId(IdWorker.getId());
            partsRel.setCreateTime(new Date());
            partsRel.setOrderId(orderId);
            partsRel.setOrderPartsId(orderParts.getId());
            partsRel.setAfterPartsId(afterPartsId);
            partsRel.setPartsMoneyRepair(partsMoneyRepair);
            partsRel.setPartsMoneyFactory(partsMoneyFactory);
            partsRel.setPartsNum(partsNum);
            partsRel.setIsSelfParts(isSelfParts);
            relList.add(partsRel);


        }
        orderParts.setPartsState(partsState);

        zsyhServiceOrderPartsService.insertZsyhServiceOrderParts(orderParts);//配件申请主表
        zsyhServiceOrderPartsRelService.insertZsyhServiceOrderPartsRelBatch(relList);//配件申请管理配件表

        ZsyhServiceOrderLog log = new ZsyhServiceOrderLog();
        log.setId(IdWorker.getId());
        log.setOrderId(orderId);
        log.setLogType("1");
        log.setLogContent("师傅申请配件");
        zsyhServiceOrderLogService.insertZsyhServiceOrderLog(log);

        ZsyhServiceOrderPartsLog partsLog = new ZsyhServiceOrderPartsLog();
        partsLog.setId(IdWorker.getId());
        partsLog.setOrderId(orderId);
        partsLog.setOrderPartsId(orderParts.getId());
        partsLog.setLogType("1");
        partsLog.setLogContent("师傅申请配件");
        zsyhServiceOrderPartsLogService.insertZsyhServiceOrderPartsLog(partsLog);

        return success("成功");
    }

    /**
     * 维修师傅 订单中心 获取配件单列表
     * @return
     * @throws Exception
     */
    @RequestMapping("/getOrderPartsList")
    @ResponseBody
    public AjaxResult getOrderPartsList(String userId, String key, String partsState, String pageNum, String pageSize)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();//师傅的店铺id

        ZsyhServiceOrderParts parts = new ZsyhServiceOrderParts();
        parts.setRepairId(repairId);
        parts.setPartsState(partsState);
        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        map.put("key", key);
        parts.setParams(map);
        List<ZsyhServiceOrderParts> partsList = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsListApplet(parts);

        return success("成功", partsList);
    }

    /**
     * 维修师傅 订单中心 获取配件单详情
     * @return
     * @throws Exception
     */
    @RequestMapping("/getOrderPartsDetails")
    @ResponseBody
    public AjaxResult getOrderPartsDetails(String orderPartsId)throws Exception
    {
        ZsyhServiceOrderParts orderParts = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsById(orderPartsId);
        return success("成功", orderParts);
    }

    /**
     * 维修师傅 订单中心 确认到货
     * @return
     * @throws Exception
     */
    @RequestMapping("/confirmArrival")
    @ResponseBody
    public AjaxResult confirmArrival(String orderPartsId)throws Exception
    {
        ZsyhServiceOrderParts orderParts = new ZsyhServiceOrderParts();
        orderParts.setId(orderPartsId);
        orderParts.setPartsState("301");
        zsyhServiceOrderPartsService.updateZsyhServiceOrderParts(orderParts);

        orderParts = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsById(orderPartsId);
        String orderId = orderParts.getOrderId();

        ZsyhServiceOrderPartsLog partsLog = new ZsyhServiceOrderPartsLog();
        partsLog.setId(IdWorker.getId());
        partsLog.setOrderId(orderId);
        partsLog.setOrderPartsId(orderParts.getId());
        partsLog.setLogType("1");
        partsLog.setLogContent("师傅确认到货");
        zsyhServiceOrderPartsLogService.insertZsyhServiceOrderPartsLog(partsLog);
        return success("成功");
    }

    /**
     * 获取物流公司
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLogisticsCompany")
    @ResponseBody
    public AjaxResult getLogisticsCompany(String key)throws Exception
    {
        ZsyhAfterLogisticsCompany company = new ZsyhAfterLogisticsCompany();
        company.setCompanyName(key);
        return success("成功", zsyhAfterLogisticsCompanyService.selectZsyhAfterLogisticsCompanyList(company));
    }

    /**
     * 回寄旧配件
     * @param orderPartsId
     * @return
     * @throws Exception
     */
    @RequestMapping("/returnAccessories")
    @ResponseBody
    public AjaxResult returnAccessories(String orderPartsId, String returnLogisticsId, String returnLogisticsName, String returnLogisticsNumber,
                                        String returnLogisticsProof, String returnLogisticsRemarks)throws Exception
    {
        ZsyhServiceOrderParts orderParts = new ZsyhServiceOrderParts();
        orderParts.setId(orderPartsId);
        orderParts.setReturnLogisticsId(returnLogisticsId);
        orderParts.setReturnLogisticsName(returnLogisticsName);
        orderParts.setReturnLogisticsNumber(returnLogisticsNumber);
        orderParts.setReturnLogisticsProof(returnLogisticsProof);
        orderParts.setReturnLogisticsRemarks(returnLogisticsRemarks);
        orderParts.setPartsState("4");
        zsyhServiceOrderPartsService.updateZsyhServiceOrderParts(orderParts);

        orderParts = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsById(orderPartsId);
        String orderId = orderParts.getOrderId();

        ZsyhServiceOrderPartsLog partsLog = new ZsyhServiceOrderPartsLog();
        partsLog.setId(IdWorker.getId());
        partsLog.setOrderId(orderId);
        partsLog.setOrderPartsId(orderParts.getId());
        partsLog.setLogType("1");
        partsLog.setLogContent("师傅回寄旧配件");
        zsyhServiceOrderPartsLogService.insertZsyhServiceOrderPartsLog(partsLog);
        return success("成功");
    }

    /**
     * 获取物流的json
     * @param orderPartsId
     * @param type 1寄件物流 2返件物流
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLogisticsJson")
    @ResponseBody
    public AjaxResult getLogisticsJson(String orderPartsId, String type)throws Exception
    {
        ZsyhServiceOrderParts orderParts = zsyhServiceOrderPartsService.getServiceOrderPartsById(orderPartsId);
        String json = "";
        if("1".equals(type)){
            String logisticsJson = String.valueOf(redisUtils.get("logistics_" + orderPartsId));
            if(EmptyUtils.isNotEmpty(logisticsJson)){
                json = logisticsJson;
            }else{
                String logisticsId = orderParts.getLogisticsId();
                String logisticsNumber = orderParts.getLogisticsNumber();
                if(EmptyUtils.isEmpty(logisticsId) || EmptyUtils.isEmpty(logisticsNumber)){
                    return error("物流单号不存在");
                }
                json = k100Utils.queryTrack(logisticsId, logisticsNumber);
                JSONObject jsonObject = JSON.parseObject(json);
                String status = String.valueOf(jsonObject.get("status"));
                if("200".equals(status)){
                    redisUtils.set("logistics_" + orderPartsId, json, 1800);
                    orderParts = new ZsyhServiceOrderParts();
                    orderParts.setId(orderPartsId);
                    orderParts.setLogisticsJson(json);
                    zsyhServiceOrderPartsService.updateZsyhServiceOrderParts(orderParts);
                }else{
                    String returnCode = String.valueOf(jsonObject.get("returnCode"));
                    if(!"200".equals(returnCode)){
                        String message = String.valueOf(jsonObject.get("message"));
                        return error(message);
                    }
                }
            }

        }else{
            String logisticsJson = String.valueOf(redisUtils.get("return_logistics_" + orderPartsId));
            if(EmptyUtils.isNotEmpty(logisticsJson)){
                json = logisticsJson;
            }else{
                String returnLogisticsId = orderParts.getReturnLogisticsId();
                String returnLogisticsNumber = orderParts.getReturnLogisticsNumber();
                if(EmptyUtils.isEmpty(returnLogisticsId) || EmptyUtils.isEmpty(returnLogisticsNumber)){
                    return error("物流单号不存在");
                }
                json = k100Utils.queryTrack(returnLogisticsId, returnLogisticsNumber);
                JSONObject jsonObject = JSON.parseObject(json);
                String status = String.valueOf(jsonObject.get("status"));
                if("200".equals(status)){
                    redisUtils.set("return_logistics_" + orderPartsId, json, 1800);
                    orderParts = new ZsyhServiceOrderParts();
                    orderParts.setId(orderPartsId);
                    orderParts.setReturnLogisticsJson(json);
                    zsyhServiceOrderPartsService.updateZsyhServiceOrderParts(orderParts);
                }else{
                    String returnCode = String.valueOf(jsonObject.get("returnCode"));
                    if(!"200".equals(returnCode)){
                        String message = String.valueOf(jsonObject.get("message"));
                        return error(message);
                    }
                }
            }
        }

        return success("获取成功", JSON.parseObject(json));

    }

}
